package com.alinesno.cloud.compoment.generate.generator.tools;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alinesno.cloud.compoment.generate.generator.StringUtils;

/**
 * 下划线和驼峰的转换
 * 
 * @author WeiXiaoJin
 * @since 2019年9月27日 上午7:00:40
 */
public class GeneratorTool {
	private static Pattern linePattern = Pattern.compile("_(\\w)");
	private static Pattern linePattern2 = Pattern.compile("-(\\w)");

	public static String toUpperCaseFirstOne(String s) {
		if (Character.isUpperCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
	}

	/** 下划线转驼峰 */
	public static String lineToHump2(String str) {
		str = str.toLowerCase();
		Matcher matcher = linePattern2.matcher(str);
		StringBuffer sb = new StringBuffer();

		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}

		matcher.appendTail(sb);
		return sb.toString();
	}

	/** 下划线转驼峰 */
	public static String lineToHump(String str) {
		str = str.toLowerCase();
		Matcher matcher = linePattern.matcher(str);
		StringBuffer sb = new StringBuffer();

		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/** 驼峰转下划线(简单写法，效率低于{@link #humpToLine2(String)}) */
	public static String humpToLine(String str) {
		return str.replaceAll("[A-Z]", "_$0").toLowerCase();
	}

	private static Pattern humpPattern = Pattern.compile("[A-Z]");

	/** 驼峰转下划线,效率比上面高 */
	public static String humpToLine2(String str) {
		Matcher matcher = humpPattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 获取字段类型
	 * @param type
	 * @return
	 */
	public static String getTypeName(String type) {
		if(StringUtils.isNotEmpty(type)) {
			if(type.contains("(")) {
				return (type.substring(0, type.indexOf("("))).toUpperCase() ; 
			}
		}
		return type.toUpperCase() ;
	}

	public static String getTypeLength(String length) {
		if(StringUtils.isNotEmpty(length)) {
			if(length.contains("(")) {
				return length.substring(length.indexOf("(")+1 , length.indexOf(")")) ; 
			}
		}
		return length ;
	}

}